// /pages/goods_cart/index.js
import {
  getReMallShopping
} from "../../../api/cart.js"
import {
    getNavigationbar
  } from "../../../api/index.js"
Page({
    options: {
        styleIsolation: 'shared'
    },
    /**
     * 页面的初始数据
     */
    data: {
        height: "",obj:{},
        isEdit: false,isAhow: false,
        scrollViewHeight: 0, // 滚动区域高度
        tabbarHeight: 0, // 底部tabbar高度
        allCheckSelVal: false, // 当前全选状态
        supCheckSelVal: false, // 当前供应商选中状态
        discount: 0,
        cartList: [{
            supId: 0,
            supName: "供应商名称供应商名称",
            supLogoUrl: "",
            check: false,
            supActivety: {
                activetyIcons: "/images/tag_dp@2x.png",
                activetyName: "满45元送养肝补血 营养膏,还差32元",
            },
            // 二级品牌列表
            supBrandList: [{
                brandId: 1,
                brandName: "品牌名称",
                brandLogoUrl: "",
                check: false,
                parentId: 0,
                brandActivety: {
                    activetyIcons: "/images/tag_dp@2x.png",
                    activetyName: "满45元送养肝补血 营养膏,还差32元",
                },
                // 三级品牌商品列表
                brandGoodsList: [{
                    goodsId: 10,
                    goodsName: "商品标题商品标题商品标题商品标题商品标题商品标题商品标题商品标题商品标题商品标题",
                    goodsImgUrl: "/images/element_christmas_xpzq@2x.png",
                    goodsSpec: [{
                        specId: 0,
                        specName: "可参加满10件送1件活动"
                    }],
                    goodsPrice: "310.0",
                    goodsCount: 1,
                    check: false,
                    parentId: 1
                }, {
                    goodsId: 11,
                    goodsName: "商品标题商品标题商品标题商品标题商品标题商品标题商品标题商品标题商品标题商品标题",
                    goodsImgUrl: "/images/element_christmas_xpzq@2x.png",
                    goodsSpec: [{
                        specId: 1,
                        specName: "可参加满10件送1件活动"
                    }],
                    goodsPrice: "318.0",
                    goodsCount: 1,
                    check: false,
                    parentId: 1
                }]
            }]
        }, {
            supId: 1,
            supName: "供应商名称1",
            supLogoUrl: "",
            check: false,
            supActivety: {
                activetyIcons: "/images/tag_dp@2x.png",
                activetyName: "满45元送养肝补血 营养膏,还差32元",
            },
            // 二级品牌列表
            supBrandList: [{
                brandId: 2,
                brandName: "品牌名称1",
                brandLogoUrl: "",
                check: false,
                parentId: 1,
                brandActivety: {
                    activetyIcons: "/images/tag_dp@2x.png",
                    activetyName: "可参加满10件送1件活动",
                },
                // 三级品牌商品列表
                brandGoodsList: [{
                    goodsId: 12,
                    goodsName: "商品标题商品标题商品标题商品标题商品标题商品标题商品标题商品标题商品标题商品标题",
                    goodsImgUrl: "/images/element_christmas_xpzq@2x.png",
                    goodsSpec: [{
                        specId: 1,
                        specName: "可参加满10件送1件活动"
                    }],
                    goodsPrice: "310.0",
                    goodsCount: 1,
                    check: false,
                    parentId: 2
                }]
            }, {
                brandId: 3,
                brandName: "品牌名称2",
                brandLogoUrl: "",
                check: false,
                parentId: 1,
                brandActivety: {
                    activetyIcons: "/images/tag_dp@2x.png",
                    activetyName: "可参加满10件送1件活动",
                },
                // 三级品牌商品列表
                brandGoodsList: [{
                    goodsId: 21,
                    goodsName: "商品标题商品标题商品标题商品标题商品标题商品标题商品标题商品标题商品标题商品标题",
                    goodsImgUrl: "/images/element_christmas_xpzq@2x.png",
                    goodsSpec: [{
                        specId: 0,
                        specName: "可参加满10件送1件活动"
                    }],
                    goodsPrice: "310.0",
                    goodsCount: 1,
                    check: false,
                    parentId: 3
                }]
            }]
        }, ],
        cartTotalPrice: "0.0", // 购物车总价格
        checkGoodsList: [],
        isSpecs: false, // 商品规格弹窗打开状态
        isPopups: false, // 默认弹窗打开状态
        showFooter: false, // 是否显示确认按钮
        popupType: "", // 弹窗类型
        isShow: false,
        addressList: [],
        address: "默认地址",    
        addressId: "",
        promoList: [{
                tags: "品牌促销",
                title: "品牌促销的活动名称文本演示",
                cxGoodsList: []
            },
            {
                tags: "品牌促销",
                title: "品牌促销的活动名称文本演示",
                cxGoodsList: [{
                        cxGoodsImg: "/images/goods-cat.jpeg",
                        cxGoodsName: "赠品的名称文本演示赠品的名称文本演示名称文本演示"
                    },
                    {
                        cxGoodsImg: "/images/goods-cat.jpeg",
                        cxGoodsName: "赠品的名称文本演示赠品的名称文本演示名称文本演示"
                    },
                    {
                        cxGoodsImg: "/images/goods-cat.jpeg",
                        cxGoodsName: "赠品的名称文本演示赠品的名称文本演示名称文本演示"
                    },
                    {
                        cxGoodsImg: "/images/goods-cat.jpeg",
                        cxGoodsName: "赠品的名称文本演示赠品的名称文本演示名称文本演示"
                    },
                ]
            },
            {
                tags: "品牌促销",
                title: "品牌促销的活动名称文本演示",
                cxGoodsList: []
            },
            {
                tags: "品牌促销",
                title: "品牌促销的活动名称文本演示",
                cxGoodsList: []
            },
            {
                tags: "品牌促销",
                title: "品牌促销的活动名称文本演示",
                cxGoodsList: []
            },
        ],
        zPactive: 1,
        showModal: false,
        isSlot: false,
        modalTitle: "",
        message: "",
        confirmText: "",
        cancelText: "",
        showCancelButton: false,
        // 模拟购物车价格变动提示
        price: 0,
        // 模拟购物赠品商品无库存时提示
        kcCount: 0,
        // 模拟购物未选赠品时提示
        zpCount: 0,
        zpList: [
           
        ],
        changePriceList: [],
        specsDetail: {},
        delList: [],
    },

    /**
     * 编辑购物车回调函数方法
     */
    handleEditCart() {
        const state = !this.data.isEdit
        this.setData({
            isEdit: state,
        })
    },
    /**
     * 打开商品规格弹窗回调函数方法
     */
    handleSelSpecs(e) {
        console.log('e', e)
        let data = {
            ...e.currentTarget.dataset.value
        }
        //详细接口
        getNavigationbar({
            act: 'good_detail',
            id : data.productid
        }).then(res => {
            data = {...res,...e.currentTarget.dataset.value}
            console.log('详细接口', data)
            this.setData({
                isSpecs: true,
                specsDetail: data
            })
        })
        wx.hideTabBar()
    },
    /**
     * 换促销回调函数方法
     */
    handleSelPromo(e) {
        const {
            type
        } = e.currentTarget.dataset
        const {
            value
        } = e.currentTarget.dataset
        if (value.offers_list) {
            value.offerList = value.offers_list
            value.offerList.forEach(item => {
                item.offerTitle = this.parseTtile(item)

            })
        }else{
            wx.nextTick(() => {
                getApp().Tips({
                    title: "暂无促销活动"
                });
                return
              });
        }

        console.log( value)
        this.setData({
            height: "880rpx",
            popupType: type,
            isPopups: true,
            popupGood: value,
        })
        wx.hideTabBar()
    },
    /**
     * 促销标题
     */
    parseTtile(value) {
        let actstr = ""
        value.buy = value.buy.replaceAll(".00", "")
        value.derate = value.derate.replaceAll(".00", "")
        switch (value.type){
            case "1":
                actstr ="满"+value.buy+"元减"+value.derate+"元"
                break
            case "2":
                console.log(value.type)
                actstr = "满"+value.buy +"元送"+value.derate+"件"
                break
            case "3":
                actstr = value.buy+ "送"+value.derate
                break
            case "4":
                actstr =value.buy + "件"+value.derate/10 +"折"
                break
            case "5":
                actstr ="满"+value.buy + "元打"+value.derate/10 +"折"
                break
            case "6":
                actstr ="满" +value.buy + "送"+value.derate
            break
        }
        console.log(value.type , actstr)
        return actstr
    },
    /**
     * 换促销回调函数方法(选择赠品)
     */
    handleSelZp(e) {
        const {
            value,cartid
        } = e.currentTarget.dataset
        console.log(value, cartid)
        getReMallShopping({
            act: 'choose_activity',
            other_detail_id: value.id,
            cartid: cartid 
        }).then(res => {
            console.log(res)
            this.getHttpReMallShopping()
        })
        this.setData({
            isPopups: false,
            isSpecs: false
        })
        getApp().$showTab()
    },
    /**
     * 更换赠品回调函数方法
     */
    handleReplaceZp(e) {
        const {
            type,good
        } = e.currentTarget.dataset
        console.log(good)
        let zpSelect = 0
        let gift = good.gift.filter(item => item.inventorys > 0)
        gift.forEach(zp => {
            zp.cartid = good.id
            zp.offersid = good.offers_info.id
        })
        if(gift.map(item => item.selected_numbers > 0)[0]) {
            zpSelect = gift.map(item => item.selected_numbers > 0).length
        }
        
        if (gift.length == 0) {
            this.setData({
                height: "256rpx",
                popupType: type,
                showFooter: true,
                isPopups: true,
            })
        } else {
            this.setData({
                height: "480rpx",
                popupType: type,
                showFooter: true,
                isPopups: true,
                zpList: gift,
                zpSelect: zpSelect
            })
        }
        getApp().$showTab()
    },
    /**
     * 弹窗确认按钮回调函数方法
     */
    handleConfirm(e){
        console.log("data", e)

        let data
        let type
        if (e.detail) {
            data = e.detail
            type = 'spec'
        } else {
            data = this.data.zpList
            type = 'zp'
        }
        console.log("data", data)
        console.log("type", type)

        if (type == 'spec') {
            this.data.cartList.forEach(item => {
                if (item.agentid == data.data.agentid) {
                    item.brand_list.forEach(brand => {
                        brand.lists.forEach(good => {
                            if (good.brandid == data.data.brandid && good.id == data.data.id) {
                                good.numbers = data.count,
                                good.propertyname = data.data.propertyname
                                good.propertyid = data.data.propertyid
    
                            }
                        })
                    })
                }
            })
            this.setData({
                cartList: this.data.cartList,
                isSpecs: false
            })
            // getReMallShopping({
            //     act: 'change_property',
            //     cart_id: data.data.id,
            //     propertyid: data.data.propertyid,

            // }).then(res => {
            //     console.log(res)
            //     if (res.result == '101') {
            //         getApp().Tips({title: res.msg})
            //     }else{
            //         getApp().Tips({title: res.msg})
            //         this.setData({
            //             cartList: this.data.cartList,
            //             isSpecs: false
            //          })
            //     }
            // }).catch(() =>{

            // })
        } else {

            let cartid 
            let offersid 
            this.data.zpList.forEach(item => {
                cartid = item.cartid
                offersid = item.offersid
            })
            console.log(this.data.zpList)
            let giftList = []
            this.data.zpList.forEach(item => {
                giftList.push({productid: item.id, number: item.selected_numbers})
            })
            console.log(cartid)
            console.log(giftList)
            if (giftList.length > 0) {
                getReMallShopping({
                    act: 'choose_activity_gifts',
                    cartid: cartid,
                    other_detail_id: offersid,
                    gift: giftList
    
                }).then(res => {
                    if (res.result == '101'){
                        getApp().Tips({title: res.msg})
                    }else{
                        this.getHttpReMallShopping()
                    }
                })
            }else{
                this.setData({
                    isPopups: false,
                })

            }
        }
        getApp().$showTab()
    },

    /**
     * 关闭弹窗回调函数方法
     */
    handleClose() {
        this.setData({
            isPopups: false,
            isSpecs: false
        })
        getApp().$showTab()
    },
    /**
     * 提示弹窗确认回调函数方法
     */
    handleModalChange(e) {
        console.log(e)
        const type = e.detail
        if (type == "confirm") {
            const handleType = e.currentTarget.dataset.type
            console.log(handleType)
            if (handleType == 'del') {
                this.delCartGoods()
            } else if (handleType == "goOrder") {
                this.goOrder()
            }
            this.setData({
                showModal: false
            })
        }
        else {
            this.setData({
                showModal: false
            })
            // getApp().Tips({ title: "操作已取消" })
        }
    },
    /**
     * 
     */
    delCartGoods() {
        getReMallShopping({
            act: 'delgoods',
            cartids: this.data.delList
        }).then(res => {
            this.getHttpReMallShopping();
        })
    },
    /**
     * 全选回调函数方法
     * @param {*} e 
     */
    allCheckSelChange(e) {
        console.log("全选", this.data.allCheckSelVal)
        // 购物车为空时无法勾选，返回重新校验
        if (this.data.cartList.length == 0) return
        let check = !this.data.allCheckSelVal
        console.log(e.detail)
        let cartids = []
        let cartList = this.data.cartList // 获取购物车数据
        this.data.checkGoodsList = []
        for (let i = 0; i < cartList.length; i++) {
            cartList[i].is_selected = check // 更改供应商选中状态
            let brandList = cartList[i].brand_list // 获取购物车供应商下品牌数据
            let mix_offers = cartList[i].mix_offers
            for (let j = 0; j < brandList.length; j++) {
                brandList[j].is_selected = check // 更改品牌选中状态
                let goodsList = brandList[j].lists
                for (let g = 0; g < goodsList.length; g++) {
                    goodsList[g].is_selected = check
                    cartids.push(goodsList[g].id)
                    if (goodsList[g].is_selected) {
                        this.data.checkGoodsList.push(goodsList[g]) // push商品选中信息形成新数组
                    } else {
                        this.data.checkGoodsList = []
                    }
                }
            }
            mix_offers.forEach(item => {
                item.brand_list.forEach(brand => {
                    brand.is_selected = check
                    brand.lists.forEach(good => {
                        good.is_selected = check
                        cartids.push(good.id)

                        if (check) {
                            this.data.checkGoodsList.push(good) // push商品选中信息形成新数组
                        }else {
                            this.data.checkGoodsList = []
                        }
                        
                    })
                })

            })
        }
        this.setData({
            allCheckSelVal: check,
            cartList: this.data.cartList,
            checkGoodsList: this.data.checkGoodsList
        })
        
        
        getReMallShopping({
            act: 'handle_cartsgoods',
            cartids: cartids,
            flag: check ? 1 : 2
        }).then(res =>{
            if (res){
                this.getHttpReMallShopping()
            }
        })
        this.getTotalPrice() // 调用购物车计算规则
    },

    /**
     * 供应商选中回调函数方法
     * @param {*} e 
     */
    supCheckSelChange(e) {
        let index = e.currentTarget.dataset.value // 获取当前供应商下标
        let cartList = this.data.cartList // 获取购物车数据
        let brandList = cartList[index].brand_list // 获取购物车供应商下品牌数据
        let mix_offers = cartList[index].mix_offers
        let flag = 1
        let cartids = []
        if (cartList[index].is_selected == 1) {
            cartList[index].is_selected = 0
            flag = 2
            // for (let i in brandList) {
            //     brandList[i].is_selected = 0
            //     let goodsList = brandList[i].lists
            //     cartids.concat(goodsList.map(good => good.id)[0])
            //     console.log(cartids)
            //     for (let j in brandList[i].lists) {
            //         brandList[i].lists[j].is_selected = 0
            //     }
            //     this.data.checkGoodsList = this.data.checkGoodsList.filter(item => !cartids.includes(item.id))
                
            // }
            brandList.forEach(brand =>{
                brand.is_selected = 0
                brand.lists.forEach(good => {
                    good.is_selected = 0
                    cartids.push(good.id)
                })
            })
            mix_offers.forEach(item => {
                item.brand_list.forEach(brand => {
                    brand.is_selected = 0
                    brand.lists.forEach(good => {
                        good.is_selected = 0
                        cartids.push(good.id)

                    })
                    
                })
            })
            this.data.checkGoodsList = this.data.checkGoodsList.filter(item => !cartids.includes(item.id))
        } else {
            cartList[index].is_selected = 1
            brandList.forEach(brand =>{
                brand.is_selected = 1
                brand.lists.forEach(good => {
                    good.is_selected = 1
                    cartids.push(good.id)
                    let a = this.data.checkGoodsList.filter(item => item.id == good.id)
                    if (a.length == 0) {
                        this.data.checkGoodsList.push(good) // push商品选中信息形成新数组
                    }
                    
                })
            })
            mix_offers.forEach(item => {
                item.brand_list.forEach(brand => {
                    brand.is_selected = 1
                    brand.lists.forEach(good => {
                        good.is_selected = 1
                        cartids.push(good.id)
                        let a = this.data.checkGoodsList.filter(item => item.id == good.id)
                        if (a.length == 0) {
                            this.data.checkGoodsList.push(good) // push商品选中信息形成新数组
                        }
                        
                    })
                })
            })
            console.log(this.data.checkGoodsList)
        }
        // 重新赋值 渲染购物车数据
        this.setData({
            cartList: this.data.cartList,
            checkGoodsList: this.data.checkGoodsList
        })
        getReMallShopping({
            act: 'handle_cartsgoods',
            cartids: cartids,
            flag: flag
        }).then(res =>{
            if (res){
                this.getHttpReMallShopping()
            }
        })
        // this.getAllCheck() // 设置全选
        // this.getTotalPrice() // 调用购物车计算规则
    },

    /**
     * 品牌选中回调函数方法
     * @param {*} e 
     */
    brandCheckSelChange(e) {
        console.log(e.currentTarget.dataset)
        let index = e.currentTarget.dataset.value // 获取当前品牌下标
        let type = e.currentTarget.dataset.type
        let cartList = this.data.cartList // 获取购物车数据
        let flag = 1
        let cartids = []

        for (let i = 0; i < cartList.length; i++) {
            if (type == "mix") {
                if (cartList[i].mix_offers.length >0) {
                    let brand_list = cartList[i].mix_offers.map(item => item.brand_list)[0]

                    console.log(cartList[i])
                    brand_list.forEach(item => {
                        if (item.brand_name == index) {
    
                           if (item.is_selected == 1) {
                                item.is_selected = 0
                                // cartList[i].is_selected =  0 // 更改供应商选中状态
                                cartids =  item.lists.map(good => good.id)
                                console.log(item.lists)
                                console.log(cartids)
                                item.lists.forEach(good => {
                                    good.is_selected = 0
                                })
                                flag = 2
                                this.data.checkGoodsList = this.data.checkGoodsList.filter(item => !cartids.includes(item.id))
                           }else{
                                item.is_selected = 1
                                // cartList[i].is_selected =  1 // 更改供应商选中状态
                                cartids =  item.lists.map(good => good.id)
                                item.lists.forEach(good => {
                                    good.is_selected = 1
                                    this.data.checkGoodsList.push(good)
                                })
                               
                           }
                            
                        }
                    })
                }

                
            }else{
                let brandList = cartList[i].brand_list
                for (let j = 0; j < brandList.length; j++) {
                  if (brandList[j].brand_name === index) {
                        let goodsList = brandList[j].lists
                        cartids = goodsList.map(good => good.id)
                        if (brandList[j].is_selected == 1) {
                            brandList[j].is_selected =  0 // 更改品牌选中状态
                            // cartList[i].is_selected =  0 // 更改供应商选中状态
                            for (let g = 0; g < goodsList.length; g++) {
                                goodsList[g].is_selected = brandList[j].is_selected // 更改品牌下的商品状态
                            }
                            flag = 2
                            this.data.checkGoodsList = this.data.checkGoodsList.filter(item => !cartids.includes(item.id))
                        } else {
                            brandList[j].is_selected = 1 // 更改品牌选中状态
                            for (let g = 0; g < goodsList.length; g++) {
                                this.data.checkGoodsList.push(goodsList[g]) // push商品选中信息形成新数组
                                goodsList[g].is_selected = brandList[j].is_selected // 更改品牌下的商品状态
                            }
                            let brandLength = cartList[i].brand_list.length // 获取供应商下品牌数量
                            let brandCheck = 0
                            for (let k in brandList) {
                                if (brandList[k].is_selected == 1) {
                                    brandCheck++
                                }
                            }
                            if (brandLength === brandCheck) {
                                // cartList[i].is_selected = 1 // 更改供应商选中状态
                            }
                        }
                }
              }
            }
        }
        // cartList.forEach(item => {
        //     item.is_selected = 1
        //     item.brand_list.forEach(brand=> {
        //         if (brand.is_selected == 0) {
        //             item.is_selected = 0
        //         }
        //     })
        //     item.mix_offers.forEach(mix => {
        //         mix.brand_list.forEach(brand => {
        //             if (brand.is_selected == 0) {
        //                 item.is_selected = 0
        //             }
        //         })
        //     })
        // })
        // 重新渲染购物车数据
        this.setData({
            cartList: this.data.cartList,
            checkGoodsList: this.data.checkGoodsList
        })
        console.log(this.data.checkGoodsList)
        getReMallShopping({
            act: 'handle_cartsgoods',
            cartids: cartids,
            flag: flag
        }).then(res =>{
            if (res){
                this.getHttpReMallShopping()
            }
        })
        // this.getAllCheck() // 设置全选
        // this.getTotalPrice() // 调用购物车计算规则
    },


    /**
     * 商品选中回调函数方法
     * @param {*} e 
     */
    goodsCheckSelChange(e) {
        let productid = e.currentTarget.dataset.value // 获取当前商品ID
        let type = e.currentTarget.dataset.type
        let cartList = this.data.cartList // 获取购物车数据
        let flag = 1
        let cartids 
        let checkGoodsList =this.data.checkGoodsList
        // let check = e.detail // 复选框状态
        for (let i = 0; i < cartList.length; i++) {
            if (type == "mix") {
                if(cartList[i].mix_offers.length > 0) {
                    let brand_list = cartList[i].mix_offers.map(item => item.brand_list)[0]
                    brand_list.forEach(brand => {
                        brand.lists.forEach (good => {
                            if (good.productid == productid) {
                                cartids = good.id
                                if (good.is_selected == 1) {
                                    good.is_selected = 0
                                    // brand.is_selected = 0
                                    // cartList[i].is_selected = 0
                                    flag = 2
                                    checkGoodsList = checkGoodsList.filter(check => check.id != cartids)
                                }else {
                                    checkGoodsList.push(good)
                                    good.is_selected = 1
                                    // brand.is_selected = 1
                                    // cartList[i].is_selected = 1
                                }
                            }
                        })
    
                    })
                }
            }else{

                let brandList = cartList[i].brand_list
                for (let j = 0; j < brandList.length; j++) {
                    let goodsList = brandList[j].lists
                    for (let g = 0; g < goodsList.length; g++) {
                        if (goodsList[g].productid === productid) {
                            // 判断当前商品是否已勾选
                            cartids = goodsList[g].id
                            if (goodsList[g].is_selected == 1) {
                                // cartList[i].is_selected = 0 // 更改供应商选中状态
                                // brandList[j].is_selected = 0 // 更改品牌选中状态
                                goodsList[g].is_selected = 0 // 更改商品选中状态
                                //取消选中
                                flag = 2
                                checkGoodsList = checkGoodsList.filter(check => check.id != cartids)
                            } else {
                                checkGoodsList.push(goodsList[g]) // push商品选中信息形成新数组
                                goodsList[g].is_selected = 1 // 更改商品选中状态
                                let goodsLength = brandList[j].lists.length // 获取品牌下商品数量
                                console.log(goodsLength)
                                let goodsCheck = 0
                                // 遍历商品数据
                                for (let k in goodsList) {
                                    if (goodsList[k].is_selected) {
                                        goodsCheck++
                                    }
                                }
                                // 根据勾选商品数据长度判断品牌是否全选
                                if (goodsLength === goodsCheck) {
                                    brandList[j].is_selected = 1
                                }
                                let brandLength = cartList[i].brand_list.length // 获取供应商下品牌数量
                                let brandCheck = 0
                                // 遍历品牌数据
                                for (let k in brandList) {
                                    if (brandList[k].is_selected) {
                                        brandCheck++
                                    }
                                }
                                // 根据勾选品牌数据长度判断供应商是否全选
                                // if (brandLength === brandCheck) {
                                    // cartList[i].is_selected = 1 // 更改供应商选中状态
                                // }
                            }
                        }
                    }
                }
            }
        }
        // cartList.forEach(item => {
        //     item.is_selected = 1
        //     item.brand_list.forEach(brand=> {
        //         brand.is_selected = 1
        //         brand.lists.forEach(good => {
        //             if (good.is_selected == 0) {
        //                 brand.is_selected = 0
        //                 item.is_selected = 0
        //             }
        //         })
        //     })
        //     item.mix_offers.forEach(mix => {
        //         mix.brand_list.forEach(brand => {
        //             brand.lists.forEach(good => {
        //                 if (good.is_selected == 0) {
        //                     brand.is_selected = 0
        //                     item.is_selected = 0
        //                 }
        //             })
        //         })
        //     })
        // })
        // 重新渲染购物车数据
        this.setData({
            cartList: this.data.cartList,
            checkGoodsList: checkGoodsList // 重新渲染选中商品存储对象数据
        })
        getReMallShopping({
            act: 'handle_cartsgoods',
            cartids: cartids,
            flag: flag
        }).then(res =>{
            if (res){
                this.getHttpReMallShopping()
            }
        })
        // this.getAllCheck() // 设置全选
        // this.getTotalPrice() // 调用购物车计算规则
    },

    /**
     * 商品数量变化回调函数方法
     * @param {*} e 
     */
    handleNumChange(e) {
        let index = e.currentTarget.dataset.value // 获取当前商品下标
        let cartList = this.data.cartList // 获取购物车数据
        console.log(e)
        let count = e.detail
        console.log(index)
        console.log(count)
        for (let i = 0; i < cartList.length; i++) {
            let brandList = cartList[i].brand_list
            for (let j = 0; j < brandList.length; j++) {
                let goodsList = brandList[j].lists
                for (let g = 0; g < goodsList.length; g++) {
                    if (goodsList[g].productid === index) {
                        goodsList[g].numbers = count // 更改商品数量
                    }
                }
            }
        }
        // 重新渲染购物车数据
        this.setData({
            cartList: this.data.cartList
        })
        this.getTotalPrice() // 调用购物车计算规则
    },

    /**
     * 赠品数量
     */
    handlezpNumChange(e) {
        const{ value } = e.currentTarget.dataset
        let num = e.detail
        this.data.zpList.forEach(item => {
            if (item.id = value.id ) {
                item.selected_numbers = num
            }
        })
        this.setData({
            zpList: this.data.zpList
        })
    },
    /**
     * 设置全选
     */
    getAllCheck() {
        let cartList = this.data.cartList // 获取购物车数据
        let length = cartList.length // 购物车数据数量长度
        let allCheckSelVal = this.data.allCheckSelVal // 当前全选状态
        let allCheck = 0
        for (let i = 0; i < cartList.length; i++) {
            if (cartList[i].is_selected == 1) {
                allCheck++
            }
        }
        if (length === allCheck) {
            allCheckSelVal = true
        } else {
            allCheckSelVal = false
        }
        console.log(allCheckSelVal)
        this.setData({
            allCheckSelVal: allCheckSelVal
        })
        this.getTotalPrice()
    },

    /**
     * 计算选中状态下供应商品牌下的商品数量及总价格
     */
    getTotalPrice() {
        console.log(this.data.checkGoodsList)
        let totalPrice = 0; // 选中商品总价格
        let totalNum = 0 // 选中商品总数量
        // let cartList = this.data.cartList // 购物车数据
        // for (let i = 0; i < cartList.length; i++) {
        //     let brandList = cartList[i].brand_list
        //     for (let j = 0; j < brandList.length; j++) {
        //         let goodsList = brandList[j].lists
        //         for (let g = 0; g < goodsList.length; g++) {
        //             // 判断商品是否选中
        //             if (goodsList[g].is_selected == 1) {
        //                 totalNum = goodsList[g].numbers
        //                 totalPrice += Number(goodsList[g].price) * totalNum
        //                 console.log(totalPrice)
        //             }
        //         }
        //     }
        // }
        this.data.checkGoodsList.forEach(item => {
            totalNum = item.numbers
            totalPrice += Number(item.price) * totalNum
        })
        this.setData({
            cartTotalPrice: totalPrice.toFixed(1)
        })
    },

    /**
     * 前往支付回调函数方法
     */
    handleToPay(e) {
        console.log("checkGoodsList", this.data.checkGoodsList);
        const {
            value
        } = e.currentTarget.dataset
        if (value) {
            // 未选择需删除商品时返回用户提示
            if (this.data.checkGoodsList.length <= 0) return getApp().Tips({
                title: '请选择需要删除的商品！'
            })
            let dels = this.data.checkGoodsList.map(item => item.id)
            
            this.setData({
                showModal: true,
                modalTitle: "删除商品",
                isSlot: false,
                message: "",
                confirmText: "确认",
                cancelText: "取消",
                showCancelButton: true,
                delList: dels,
                modalType: 'del',
            })
            wx.showModal({
                title: '删除商品',
                content: '当前操作将做商品删除处理！是否继续执行？',
                showCancel: false,
                success(res) {
                    if (res.confirm) {
                        wx.navigateBack()
                    }
                }
            })
        } else {
            // 未选择商品时返回用户提示
            console.log("已经选择的", this.data.checkGoodsList)
            if (this.data.checkGoodsList.length <= 0) return getApp().Tips({
                title: '请选择商品！'
            })
            // if (this.data.kcCount <= 0) {
            //     this.setData({
            //         showModal: true,
            //         modalTitle: "库存不足",
            //         isSlot: false,
            //         message: "赠品【赠品商品名称文本演示】已无库存，请重新选择赠品或清空赠品继续下单",
            //         confirmText: "继续下单",
            //         cancelText: "重新选择",
            //         showCancelButton: true,
            //         modalType: "goOrder"
            //     })
            // }
            // if (this.data.zpCount <= 0) {
            //     this.setData({
            //         showModal: true,
            //         modalTitle: "未选赠品",
            //         isSlot: false,
            //         message: "您已满足活动条件，但尚未选择赠品！是否继续支付？",
            //         confirmText: "确认",
            //         cancelText: "取消",
            //         showCancelButton: true,
            //         modalType: "goPay"

            //     })
            // }
            console.log(this.data.checkGoodsList)

            let check = this.data.checkGoodsList
            let noinventory = [] 
            let notchoose = []
            for(let i = 0; i < check.length; i++){
                if (check[i].gift && check[i].gift.length > 0) {
                    for(let j = 0;j < check[i].gift.length; j++){
                        if (check[i].gift[j].inventorys == 0) {
                            noinventory.push(check[i].gift[j].name)
                        }else{
                            if (check[i].gift[j].selected_numbers == 0) {
                                notchoose.push(check[i].gift[j].name)
                            }
                        }
                    }
                }
            }
            if (noinventory.length > 0) {
                let names
                if (noinventory.length <= 3) {
                    names = noinventory.join("，")
                }else{
                    names = noinventory.slice(0, 3).join("，")+"..."

                }
                this.setData({
                    showModal: true,
                    modalTitle: "库存不足",
                    isSlot: false,
                    message: "赠品【"+names+"】已无库存，请重新选择赠品或清空赠品继续下单",
                    confirmText: "继续下单",
                    cancelText: "重新选择",
                    showCancelButton: true,
                    modalType: "goOrder"
                })
            }else{
                this.goOrder()
            }
            if (notchoose.length > 0) {
                this.setData({
                    showModal: true,
                    modalTitle: "库存不足",
                    isSlot: false,
                    message: "存在已满足的满赠活动但并未选择，是否继续下单？",
                    confirmText: "继续下单",
                    cancelText: "重新选择",
                    showCancelButton: true,
                    modalType: "goOrder"
                })
            }else{
                this.goOrder()
            }
            
        }
    },
    goOrder(){
        // 前往支付订单页面执行支付请求
            let count = this.data.checkGoodsList.length
            let data = {
                addressId: this.data.addressId,
                totalNumbers: count,
                type: 'cart'
            }
            let objStr = JSON.stringify(data);

            wx.navigateTo({
                url: '/subpackages/pages/confirm_order_shipping/index?data=' + objStr
            })
    },
    /**
     * 删除购物车商品回调函数方法
     * @param {*} e 
     */
    handleDelCartGoods(e) {
        const {
            value
        } = e.currentTarget.dataset // 获取需的删除当前商品数据
        console.log(value)
        this.setData({
            showModal: true,
            modalTitle: "删除商品",
            isSlot: false,
            message: "当前操作将做商品删除处理！是否继续执行？",
            confirmText: "确认",
            cancelText: "取消",
            showCancelButton: true,
            modalType: 'del',
            delList: value.id
        })
    },
    /**
     * 计算页面可滚动区域的动态高度
     */
    computeScrollViewHeight() {
        let that = this
        let query = wx.createSelectorQuery().in(this)
        query.select('.header').boundingClientRect()
        query.select('.footer').boundingClientRect()
        query.exec(res => {
            let headerHeight = res[0].height;
            let footerHeight = res[1].height;
            let winHeight; // 窗口可使用高度
            let tabbarHeight; // 底部导航高度
            // let navTopHeight = headerHeight + tabsHeight
            wx.getSystemInfo({
                success: (res) => {
                    winHeight = res.windowHeight
                    tabbarHeight = res.windowHeight - res.safeArea.bottom + 50 // 计算底部导航总高度比变化
                }
            })
            let scrollHeight = winHeight - headerHeight - footerHeight - tabbarHeight;
            // 滚动区域高度
            that.setData({
                scrollViewHeight: scrollHeight,
                tabbarHeight: tabbarHeight
            })
        })
    },

    /**
     * 获取购物车展示列表
     * @param {*} address_id //商品id 
     */
    getHttpReMallShopping() {
        console.log(this.data.addressId)
      getReMallShopping({
          act: 'cart_list',
          address_id: this.data.addressId,
      }).then(res => {
        
        console.log(res)
          if (res) {
            let checkList = []
            
            //促销数据整理
            res.lists.forEach(item => {
                //混合促销
                if (item.mix_offers.length > 0) {
                    item.mix_offers.forEach(mix => {
                        mix.offers_info.offerTitle = this.parseTtile(mix.offers_info)
                        mix.brand_list.forEach(brand => {
                            brand.lists.forEach(good => {
                                good.hasgift = false
                                good.offers_list.forEach( off => {
                                    if (off.activetype == 1 && off.gift.length > 0 && off.is_selected == 1) {
                                        good.hasgift = true
                                        good.gift = off.gift
                                    }
                                })
                            })
                        })
                    })
                } 
                if (item.brand_list.length > 0){
                    //品牌促销
                    item.brand_list.forEach(brand => {
                        if (brand.offers.length > 0) {
                            let offerList = brand.offers.map(off => off.offers_info)
                            brand.offers.forEach(off => {
                                off.lists.forEach(o => {
                                    brand.lists.push(o)

                                })
                            })
                            offerList.forEach(i => i.offerTitle = this.parseTtile(i))
                            brand.offerList = offerList
                        }
                        brand.lists.forEach(good => {
                            good.hasgift = false
                                good.offers_list.forEach( off => {
                                    if (off.activetype == 1 && off.gift.length > 0 && off.is_selected == 1) {
                                        good.hasgift = true
                                        good.gift = off.gift
                                    }
                                })
                        })
                    })
                }
            })
            let checkAll = true
            //选中
            res.lists.forEach(item => {
                item.brand_list.forEach(brand => {
                    brand.lists.forEach(good => {
                        if (good.is_selected == 1) {
                            checkList.push(good)
                        }
                    })
                })
                item.mix_offers.forEach(mix => {
                    mix.brand_list.forEach(brand => {
                        brand.lists.forEach(good => {
                            console.log(good.is_selected)
                            if (good.is_selected == 1) {
                                checkList.push(good)
                            }
                        })
                    })
                })
                    
            })
            resfor: for (let i =0; i<res.lists.length;i++) {
                let brand = res.lists[i].brand_list
                for (let j=0; j<brand.length;j++){
                    let good = brand[j].lists
                    for(let h=0; h<good.length;h++){
                        if (good[h].is_selected == 0) {
                            checkAll = false
                            break resfor;
                        }
                    }
                }
                let mix = res.lists[i].mix_offers
                for (let j=0; j<mix.length;j++){
                    let brand = mix[j].brand_list
                    for(let h=0; h<brand.length;h++){
                        let good = brand[h].lists
                        for(let k=0; k<good.length;k++){
                            if (good[h].is_selected == 0) {
                                checkAll = false
                                res.lists[i].is_selected = 0
                                break resfor;
                                
                            }
                        }
                    }
                }

            }

            let discount = 0
            res.lists.forEach(item =>{
                discount += item.discount
                console.log("--------------",item.discount)
                item.brand_list.forEach(brand => {
                    brand.lists.forEach(good => {
                        good.brand_name = brand.brand_name
                        good.agent_name = item.agent_name
                    })
                })
            })
            console.log(discount)
            if ( discount > 0) {
                this.data.discount = discount.toFixed(2)
            }else{
                this.data.discount = 0
            }
           
            this.setData({
                cartList: res.lists,
                changePriceList: res.change_price,
                showModal: res.change_price.length > 0,
                modalTitle: "购物车价格变动提醒",
                isSlot: true,
                confirmText: "我知道了",
                checkGoodsList: checkList,
                allCheckSelVal: checkAll,
                discount: this.data.discount
            })
            console.log(this.data.discount)
          
        //   this.getAllCheck() // 设置全选
          this.getTotalPrice() // 调用购物车计算规则
          }
      })
  },
   /**
     * 头部导航左侧内容点击回调函数方法
     */
   handleSelAddress() {
    wx.nextTick(() => {
        this.setData({
            isAddress: true,
            })
        })
        
    },
    getAddress() {
        
        if (this.data.obj.shop_status == 0 || this.data.obj.shop_status == 1) {
            this.setData({
                isAhow: true,
            })
            return
        }
        getNavigationbar({
            act: "addressres",
            type: "getlist",
        }).then(res => {
            if (res) {
                res.forEach(item => {
                    item.userAddress = item.province + item.city + item.county
                })
                let addr = res.find(item => item.is_default == "1")
                wx.nextTick(() => {
                    this.setData({
                        addressList: res,
                        address: addr.userAddress,
                        addressId: addr.id
                    })
                    this.getHttpReMallShopping();
                })
            }
        })  

    },
    check(e){

        console.log(e)
        const data = e.detail
        this.setData({
            isAddress: false,
            address: data.userAddress,
            addressId: data.id
        })
        this.getHttpReMallShopping()

    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let res = wx.getStorageSync('USER')
        this.data.obj = res
       
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getAddress()
        this.computeScrollViewHeight();
        
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})